package org.ezplatform.office.questionnaire.web.rest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.core.annotation.AppLog;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/w/questionnaire/answerStatus")
public class QuestionnairAnswerStatusWebApiController extends BaseController<QusetionnaireAnswerStatus,String>{
	
	@Autowired
	private QuestionnaireAnswerStatusService statusService;
	
	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	private SendMsgUtils sendMsgUtils;
	
	@Override
	protected BaseService<QusetionnaireAnswerStatus, String> getEntityService() {
		return statusService;
	}
	
	/**
	 * 回退问卷
	 * @param ids
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/reply", method = RequestMethod.POST)
	@ResponseBody
	@AppLog
	public OperationResult reply(HttpServletRequest request,Model model, @RequestParam("ids") String ids, @RequestParam("quesitionnaireId") String quesitionnaireId) {
		WebUser user = WebUtils.getCurrentUser();
		String backReason = request.getParameter("backReason");
		List<String> list = new ArrayList<String>();
		List<String> userIdList = new ArrayList<String>();
		List<QusetionnaireAnswerStatus> qasList = statusService.findByIds(Arrays.asList(ids.split(",")));
		if(CollectionUtils.isNotEmpty(qasList)) {
			for(QusetionnaireAnswerStatus qas : qasList) {
				if("1".equals(qas.getStatus())) {//只回退已提交的（防止移动端同步操作）
					list.add(qas.getId());
					userIdList.add(qas.getCreatedBy());
				}
			}
		}
		if(list.size() > 0) {
			//回退
			statusService.replyQusetionnaireByIds(backReason, list);
			//回退问卷推送
			Map<String,Object> map = new HashMap<>();
			Questionnaire questionnaire = questionnaireService.findOne(quesitionnaireId);
			//问卷名称
			map.put("quesName",questionnaire.getName());
			//问卷结束时间
			map.put("closeDate",questionnaire.getCloseDate());
			map.put("quesId",quesitionnaireId);
			map.put("backReason", backReason);
			StringBuffer userIdsBuilder = new StringBuffer();
			StringBuffer jsonIdsBuilder = new StringBuffer("[");
			for(String id : userIdList){
				userIdsBuilder.append(id).append(",");
				jsonIdsBuilder.append("{\"10\":\"").append(id).append("\"},");
			}
			String userIds = userIdsBuilder.toString();
			String jsonIds = jsonIdsBuilder.toString();
			if(userIds.length() > 1 && userIds.charAt(userIds.length() - 1) == ',') {
				userIds = userIds.substring(0, userIds.length() - 1);
				jsonIds = jsonIds.substring(0, jsonIds.length() - 1);
			}
			jsonIds += "]";
			map.put("userIds",userIds);
			map.put("type", SendMsgUtils.REPLYSTATUS);
			sendMsgUtils.sendMsgToApp(user.getCorpId(),user.getJwtToken(),map,request,user.getUserId());
	
			Map<String,String> paramMap = new HashMap<>();
			paramMap.put("userId",user.getUserId());
			paramMap.put("corpId",user.getCorpId());
			paramMap.put("token", user.getJwtToken());
			paramMap.put("msgTitle",SendMsgUtils.REPLY_FOR_HOA+questionnaire.getName());
			paramMap.put("dataId", UuidUtils.UUID());
			paramMap.put("msgContent",SendMsgUtils.REPLY_FOR_HOA+questionnaire.getName());
			paramMap.put("url",SendMsgUtils.QUES_ANSWER_URL);
			paramMap.put("quesitionnaireId",quesitionnaireId);
			paramMap.put("msgReceiver",jsonIds);
			sendMsgUtils.sendMsgToOffice(paramMap);
		}
		return OperationResult.buildSuccessResult("回退成功");
	}
	
	/**
	 * 一键提醒未答卷
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/noAnswerRemind", method = RequestMethod.POST)
	@ResponseBody
	@AppLog
	public OperationResult noAnswerRemind(HttpServletRequest request,Model model, @RequestParam("quesitionnaireId") String quesitionnaireId, @RequestParam("ids") String ids) {
		WebUser user = WebUtils.getCurrentUser();
		if(ids != null) {
			String[] idsArray = ids.split(",");
			//回退问卷推送
			Map<String,Object> map = new HashMap<>();
			Questionnaire questionnaire = questionnaireService.findOne(quesitionnaireId);
			//问卷名称
			map.put("quesName",questionnaire.getName());
			//问卷结束时间
			map.put("closeDate",questionnaire.getCloseDate());
			map.put("quesId",quesitionnaireId);
			StringBuffer userIdsBuilder = new StringBuffer();
			StringBuffer jsonIdsBuilder = new StringBuffer("[");
			for(String id : idsArray){
				if(!userIdsBuilder.toString().contains(id)) {
					userIdsBuilder.append(id).append(",");
					jsonIdsBuilder.append("{\"10\":\"").append(id).append("\"},");
				}
			}
			String userIds = userIdsBuilder.toString();
			String jsonIds = jsonIdsBuilder.toString();
			if(userIds.length() > 1 && userIds.charAt(userIds.length() - 1) == ',') {
				userIds = userIds.substring(0, userIds.length() - 1);
				jsonIds = jsonIds.substring(0, jsonIds.length() - 1);
			}
			jsonIds += "]";
			map.put("userIds",userIds);
			map.put("type", SendMsgUtils.OVER_DUE);
			map.put("remindTarget", questionnaire.getRemindTarget());
			sendMsgUtils.sendMsgToApp(user.getCorpId(),user.getJwtToken(),map,request,user.getUserId());

			Map<String,String> paramMap = new HashMap<>();
			paramMap.put("userId",user.getUserId());
			paramMap.put("corpId",user.getCorpId());
			paramMap.put("token", user.getJwtToken());
			paramMap.put("msgTitle","您有一份问卷截止日期要到了："+questionnaire.getName());
			paramMap.put("dataId", UuidUtils.UUID());
			paramMap.put("msgContent","您有一份问卷截止日期要到了："+questionnaire.getName());
			paramMap.put("url",SendMsgUtils.QUES_ANSWER_URL);
			paramMap.put("quesitionnaireId",quesitionnaireId);
			paramMap.put("msgReceiver",jsonIds);
			sendMsgUtils.sendMsgToOffice(paramMap);
		}
		
		return OperationResult.buildSuccessResult("提醒成功");
	}
	
	/**
	 * 获取回退原因
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getBackReason", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getBackReason(@RequestParam("id") String id, HttpServletRequest request) {
		QusetionnaireAnswerStatus qas = statusService.findOne(id);
		return OperationResult.buildSuccessResult(qas.getBackReason());
    }
	
	/**
	 * 提交成绩
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/saveGrade", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult saveGrade(HttpServletRequest request, @RequestParam("quesitionnaireId") String quesitionnaireId, 
			@RequestParam("userId") String userId, @RequestParam("grade") String grade) {
		try {
			QusetionnaireAnswerStatus answerStatus = statusService.findAnswerStatus(userId,quesitionnaireId);
			answerStatus.setStatus("1");
			if(StringUtils.isNotEmpty(grade)) answerStatus.setGrade(Float.parseFloat(grade));
			statusService.save(answerStatus);
			statusService.rankingByGrade(quesitionnaireId);
			return OperationResult.buildSuccessResult("上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildSuccessResult("上传出错");
		}
	}
	
	/**
	 * 获取成绩排名
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "/getRankingList", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> getRankingList(HttpServletRequest request) {
		String quesId = ValidateUtils.filter(request.getParameter("quesId"));
		String userName = request.getParameter("userName");
		String orgName = request.getParameter("orgName");
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		return statusService.getRankingList(quesId, pageable, userName, orgName);
    }
}